package com.cloudmusic.service.impl;

import com.cloudmusic.constant.EnvConfig;
import com.cloudmusic.dao.UploadMapper;
import com.cloudmusic.entity.Music;
import com.cloudmusic.utils.lrc.HttpClientUtil;
import com.cloudmusic.service.UploadService;
import com.cloudmusic.utils.MD5Util;
import com.cloudmusic.utils.Mp3Util;
import com.cloudmusic.utils.MusicAnalysis;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.net.URLEncoder;

@Service
@Transactional
public class UploadServiceimpl implements UploadService {

    private Logger logger=Logger.getLogger(this.getClass());

    @Autowired
    UploadMapper uploadMapper;

    @Override
    public void uploadMusic(Music music) {
        uploadMapper.saveSongInformation(music.getSid(),music.getFile_name(),music.getSong_name(),
                music.getDuration(),music.getBitRate(),music.getAuthor(),music.getAlbum(),
                music.getYear(),music.getLocalLoc(),music.getImg(),music.getLrc());
    }

    @Override
    public boolean checkmusic(String sid) {
        int i = uploadMapper.checkmusic(sid);
        if(i == 1){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Music musicanalysis(File file) {
        Music music = new Music();
        MusicAnalysis musicAnalysis = new MusicAnalysis();
        try{
            //一、对文件进行信息解析，装进实体类对象之中
            music = musicAnalysis.getMusicInfo(file);
            music.setSid(MD5Util.getFileMD5(file));
            music.setLocalLoc(file.getAbsolutePath());
            //若无歌曲名信息，给歌曲名赋值为文件名
            if(music.getSong_name() == null || music.getSong_name().equals("")) {
                music.setSong_name(music.getFile_name());
            }
            //未知歌手
            if(music.getAuthor() == null || music.getAuthor().equals("")) {
                String author = "群星";
                author = new String(author.getBytes(),"GBK");
                music.setAuthor(author);
            }
            //未知专辑
            if(music.getAlbum() == null || music.getAlbum().equals("")) {
                String album = "未知专辑";
                album = new String(album.getBytes(),"GBK");
                music.setAlbum(album);
            }
            //二、解析文件中的专辑图片并保存，存储其路径
            try{
                String jpgfilepath = EnvConfig.getString("MUSIC_LOCATION")+"/musicjpg";
                String mp3jpgfilepath = Mp3Util.saveMP3Image(file,jpgfilepath,true);
                if(mp3jpgfilepath != null && mp3jpgfilepath.length() != 0){
                    music.setImg(mp3jpgfilepath);
                }else{
                    music.setImg(null);
                }
            }catch (Exception e){
                logger.info("歌曲无专辑图片");
            }
            //三、从网络爬取歌曲歌词并保存s
            try{
                //获得歌曲演唱者
                String musicauthor = music.getAuthor();
                //获得歌曲文件名
                String musicfilename = music.getFile_name();
                //获得歌词存储的位置D:/CloudMusicFile/musiclrc
                String lrcsavepath = EnvConfig.getString("MUSIC_LOCATION")+"/musiclrc";
                HttpClientUtil clientUtil=HttpClientUtil.getInstance();
                //获取歌曲名
                String songName=music.getSong_name();
                //获取爬取歌词网站地址
                String page = HttpClientUtil.getPage("http://geci.9ku.com/geci/"+ URLEncoder.encode(songName, "utf-8") +"/");
                String newpage = new String(page.getBytes(),"utf-8");
                System.out.println(newpage);
                Document document = Jsoup.parse(newpage);
                Elements select = document.select(".lrcList");
                //遍历查找列表符合条件的歌曲歌词信息
                select.select("li").forEach(element -> {
                    System.out.println(element.select(".tGequ").text());
                    String href = element.select(".tGequ").attr("href");
                    int ii = href.lastIndexOf("/");
                    String id = href.substring(ii+1, href.lastIndexOf("."));
                    System.out.println(id);
                    String discript = element.select(".soLrcB").text();
                    System.out.println(discript);
                    ////歌曲匹配作者姓名下载歌词文件
                    if (discript.contains(musicauthor)){
                        String url="http://www.9ku.com/downlrc.php?id="+id;
                        String lrc = lrcsavepath+"/"+musicfilename+".lrc";
                        HttpClientUtil.httpDownloadFile(url,lrc);
                        System.out.println("已下载");
                    }
                    System.out.println("-----------");
                });
                String lrcpath = lrcsavepath+"/"+musicfilename+".lrc";
                File lrcfile = new File (lrcpath);
                if (lrcfile.exists()){
                    music.setLrc(lrcpath);
                }
            }catch (Exception e){
                logger.info("歌曲无歌词信息");
            }
        }catch (Exception e){
            e.printStackTrace();
            return music;
        }
        return music;
    }


}
